<template>
  <div>
    <!-- 单图片上传，点击直接覆盖上传 -->
    <template v-if="limit === 1 && props.type === 'image'">
      <div v-if="model?.[0]?.url" class="single-uploader-image">
        <img :src="model?.[0]?.url" class="image" />
        <div class="image-close" @click="onRemoveSingleImage"></div>
        <div class="image-enlarge" @click.stop="onPreview(model?.[0])">点击查看大图</div>
      </div>
      <el-upload
        v-else
        v-bind="props"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :class="['single-uploader', model?.[0]?.url ? 'single-uploader-image' : '']"
      >
        <el-icon class="file-uploader-icon">
          <Plus />
          <div v-if="props.inlineTip" class="inline-tip">
            {{ props.inlineTip }}
          </div>
        </el-icon>
      </el-upload>
      <div class="el-upload__tip">{{ tip }}</div>
    </template>

    <!-- 多图片上传，默认支持预览，若需不支持预览，后续优化 -->
    <el-upload
      v-else-if="limit > 1 && props.type === 'image'"
      v-bind="props"
      ref="multiplyUploadRef"
      list-type="picture-card"
      :disabled="fileList.length >= limit"
      :file-list="fileList"
      :before-upload="beforeUpload"
    >
      <el-icon class="file-uploader-icon">
        <Plus />
        <div v-if="props.inlineTip" class="inline-tip">
          {{ props.inlineTip }}
        </div>
      </el-icon>

      <template #file="{ file, index }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <div v-if="!disabled" class="image-close" @click="onRemoveByIndex(index)"></div>
            <div v-if="props.preview" class="image-enlarge" @click.stop="onPreview(file)">
              点击查看大图
            </div>
          </span>
        </div>
      </template>

      <template #tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>

    <!-- Excel上传 -->
    <el-upload
      v-if="props.type === 'excel'"
      v-bind="props"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="onRemove"
      :on-preview="onPreviewExcel"
    >
      <el-button :disabled="limit > 0 && fileList.length >= limit">上传文件</el-button>
      <template #tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>
  </div>
  <div v-if="dialogVisible" class="dialog">
    <img :src="dialogImageUrl" class="image" />
    <el-icon class="close-icon" @click="dialogVisible = false"
      ><CircleCloseFilled style="width: 100%; height: 100%"
    /></el-icon>
  </div>
</template>

<script lang="tsx" setup>
import { uploadImage } from '@/apis/upload'
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'
import { Plus, CircleCloseFilled } from '@element-plus/icons-vue'

interface IProps {
  // 允许上传文件的最大数量，0表示不限制
  limit?: number
  // 上传类型 图片 excel
  type?: 'image' | 'excel'
  // 允许上传文件的最大大小, 单位MB，0表示不限制
  maxSize?: number
  // 允许上传文件的类型，默认为图片类型
  accept?: string
  // 是否禁用
  disabled?: boolean
  // 是否支持多选
  multiple?: boolean
  // 是否支持预览
  preview?: boolean
  // upload组件插槽tip
  tip?: string
  // 单图片上传时，方框内的提示文字
  inlineTip?: string
}

const model = defineModel<any>()
const props = withDefaults(defineProps<IProps>(), {
  limit: 1,
  type: 'image',
  maxSize: 0,
  accept: '*',
  disabled: false,
  multiple: false,
  preview: true,
  tip: '尺寸不限，最大5M，类型jpg、png',
  inlineTip: '',
})
const fileList = ref<any>([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const multiplyUploadRef = ref<any>()

const beforeUpload = async (file: File) => {
  const size = file.size / 1024 / 1024
  if (props.maxSize > 0 && size > props.maxSize) {
    ElMessage.error('图片大小超出限制')
    return false
  }
  const type = file.name.split('.')[1]
  if (props.accept !== '*' && !props.accept.includes(type!)) {
    ElMessage.error('文件格式有误')
    return false
  }
  const res = await uploadImage(file)
  if (res.code === '0000') {
    const result = {
      name: file.name,
      url: res.data?.absolutePath,
      relativePath: res.data?.relativePath,
    }
    fileList.value = fileList.value.concat(result)
    model.value = (props.limit === 1 ? [] : model.value).concat(result)
    return true
  }
  return false
}

const onPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const onRemove = (file: any, _fileList: any) => {
  model.value = [].concat(_fileList)
}

const onRemoveSingleImage = (e: any) => {
  e.stopPropagation()
  model.value = []
}

const onRemoveByIndex = (index: number) => {
  model.value.splice(index, 1)
}

const onPreviewExcel = (file: any) => {
  window.open(file.url)
}

// 初始化时同步fileList
watch(model, (value) => {
  fileList.value = value
})
</script>

<style lang="scss" scoped>
.single-uploader {
  :deep(.el-upload) {
    border: 1px dashed #2072ff;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    background-color: #f4f8ff;
    display: flex;
    width: 80px;
    height: 80px;
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
  .file-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
}
.single-uploader-image {
  position: relative;
  border: 1px solid #dcdfe6;
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  .image {
    width: 80px;
    height: 80px;
    object-fit: contain;
  }
}

.image-close {
  width: 16px;
  height: 16px;
  background: url('../assets/icons/close.png') no-repeat;
  background-size: contain;
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}
.image-enlarge {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: #000000;
  opacity: 0.7;
  font-size: 12px;
  text-align: center;
  line-height: 24px;
  height: 24px;
  color: #fff;
  cursor: pointer;
}

.el-icon.file-uploader-icon {
  font-size: 20px;
  color: #2072ff;
  width: 80px;
  height: 80px;
  text-align: center;
  display: flex;
  flex-direction: column;
  .inline-tip {
    font-size: 12px;
  }
}
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  background-color: #f4f8ff;
  border: 1px dashed #2072ff;
}
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
:deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
  opacity: 1;
  background: transparent;
}
:deep(.el-upload-list--picture-card .el-upload-list__item-actions span) {
  display: block;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: scroll;
  z-index: 1000;
  .image {
    width: 60%;
    object-fit: contain;
  }
  .close-icon {
    position: absolute;
    width: 44px;
    height: 44px;
    right: 40px;
    top: 40px;
    &:hover {
      cursor: pointer;
    }
  }
}

.image-close-icon {
  position: absolute;
  top: 0;
  right: 0;
}

:deep(.el-icon--close-tip) {
  display: none !important;
}
.el-upload__tip {
  font-size: 12px;
  color: #222;
}
</style>
